'''
[--------> Email Tool <-------]
exmple:
--------------------------------------------------------------
e = Email()
e.addTitle(from_='房东的猫', subject='《美好事物》+网页')
list = ['热夏 你归来 听蝉', '再游于 北方 知寒', '沿途不 枉为 少年',
         '终有个 结局 圆满', '你看 顽皮细雨招摇 过 远 帆', 
         '修理过小店 某处忽明忽暗的 灯 盏', '你听 江水流过人家 吵着要 上 岸']
e.addPlain('\n'.join(list))
e.addImage(r'picture\壁纸5 - 小猫咪.jpg','littercat.jpg')
e.addFile(r'file\新三板的测试案例.xlsx')
e.sendMail(['xxxxxx001@163.com','xxxxxx002@qq.com'])
---------------------------------------------------------------
'''
__author__ = 'Xiaossiiii'

import os
import smtplib
import logging
from time import sleep
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

logging.basicConfig(format='%(asctime)s %(name)s [Line: %(lineno)d] %(message)s',
                            level=logging.DEBUG,
                            )

class Email:

    # Account + Passwd
    mailAccount = '84068xxxxx@qq.com'
    mailPasswd= 'ejjxxxwpvxxxcgg'
    # If send faild, retry {retryTimes} times
    retryTimes = 5

def __init__(self):
        '''
        Login in, with Default Account and Passwd in Code
        '''
        self.mail =smtplib.SMTP('smtp.qq.com', 25)
        self.mail.login(self.mailAccount, self.mailPasswd)
        logging.debug(f'Account [ {self.mailAccount} ] logged in sucessfully.')

    def addTitle(self, from_='所以年少人', subject='遇见你的时候所有星星都落到我头上'):
        '''
        add Email Title via This Function
        :param from_: String, Which Refers to Who are you
        :param subject: The Subject of Email, Like Spring Title Upper
        :return: None
        '''
        self.mainBody = MIMEMultipart('mixed')
        # Email Header and Trailer
        self.mainBody['From'] = '%s<%s>' % (from_, self.mailAccount)
        # self.mainBody['To'] = ''
        # Subject of Email --> [Variable]
        self.mainBody['subject'] = Header(subject, 'utf-8')
        logging.debug(f'mainBody set From as [ {from_} ] ...')
        logging.debug(f'mainBody set Subject as [ {subject} ] ...')

    def addPlain(self, content:str):
        '''
        text Content
        :param content: String, text Content
        :return:None
        '''
        plainBody = MIMEText(content, 'plain', 'utf-8')
        self.mainBody.attach(plainBody)
        message = content[0:10].replace('\n','') if len(content) >10 else content.replace('\n','')
        logging.debug(f'mainBody attached [ {message} ] ...')

    def addHtml(self,filename, html_info:str):
        '''
        add HTML Content to Email mainBody
        :param filename: Send HTML File Name, Must Consistans with AlphaBet and Digit
        :param html_info: HTML Detail textPlain Data
        '''
        htmlBody = MIMEText(html_info, 'html', 'utf-8')
        if not os.path.basename(filename).endswith('.html'):
            filename += '.html'
        htmlBody.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', filename))
        # Add Content to mainBody
        self.mainBody.attach(htmlBody)
        logging.debug(f'mainBody attached HTML File named [ {filename} ] ...')

    def addImage(self, imagePath, imageName=None):
        '''
        add Image / Picture to Email mainBody
        '''
        image = open(imagePath, 'rb').read()
        imageBody = MIMEImage(image)
        
        if imageName:
            if not os.path.basename(imageName).endswith(os.path.splitext(imagePath)[-1]):
                imageName += os.path.splitext(imagePath)[-1]
        else:
            imageName = os.path.basename(imagePath)

        imageBody.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', imageName))
        self.mainBody.attach(imageBody)
        logging.debug(f'mainBody attached Image File named [ {imageName} ] ...')

    def addFile(self, filePath, filename=None):
        '''
        add a single File to Email mainBody
        :param filePath: The File You Want to Send
        :param rename: You Can Rename The File You Provide a New Name
        '''
        file = open(filePath, 'rb').read()
        binaryBody = MIMEText(file, 'base64', 'utf-8')
        binaryBody["Content-Type"] = 'application/octet-stream'
            
        if filename:
            if not os.path.basename(filename).endswith(os.path.splitext(filePath)[-1]):
                filename += os.path.splitext(filePath)[-1]
        else:
            filename = os.path.basename(filePath)

        binaryBody.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', filename))
        self.mainBody.attach(binaryBody)
        logging.debug(f'mainBody attached Binary File named [ {filename} ] ...')

    def addFiles(self, dirPath):
        '''
        add a List of Directory Files to Email Body
        :param dirPath: The Directory You Want To Send
        '''
        for (dirpath, dirnames, filenames) in os.walk(dirPath):
            for file in filenames:
                self.addFile(os.path.join(dirpath, file))

    def sendMail(self, toUser:any):
        # Repeat 5 times If Error
        currentTimes = self.retryTimes

        while currentTimes > 0:
            try:
                self.mail.sendmail(self.mailAccount, toUser, self.mainBody.as_string())
                logging.debug('Sendemail Successfully !')
                currentTimes = 0
            except:
                currentTimes -= 1
                logging.debug(f'Total {self.retryTimes} time, the {self.retryTimes - currentTimes } times retry to send...')
                sleep(30)

        self.mail.quit()
        logging.debug(f'Account [ {self.mailAccount} ] logged out sucessfully.')
        

class ScreenShot:

    from PIL import ImageGrab

    def __init__(self, imageName, dirPath=None):
        '''
        Get a Screent Shot on Current Enveronment
        :param dirPath:the position you want to save your Image in
        :param imageName: ImageName, type String
        '''
        pic = self.ImageGrab.grab()
        if not os.path.basename(imageName).endswith('.jpg'):
            imageName = imageName + '.jpg'
        if dirPath:
            os.makedirs(dirPath, exist_ok=True)
            pic.save(os.path.join(dirPath, imageName))
        else:
            pic.save(imageName)



if __name__ == '__main__':
    import requests
    e = Email()
    e.addTitle(from_='房东的猫', subject='《美好事物》+网页')
    list = ['热夏 你归来 听蝉', '再游于 北方 知寒', '沿途不 枉为 少年', '终有个 结局 圆满',
            '你看 顽皮细雨招摇 过 远 帆', '修理过小店 某处忽明忽暗的 灯 盏', '你听 江水流过人家 吵着要 上 岸',
            '你去过 烟花三月的江南', '你看 秋月温柔撕破了 花 瓣', '却只为 迎着暮冬大雪纷飞时 贪 玩','你说 要忘却所有 不愉快的 片 段',]
    e.addPlain('\n'.join(list))
    e.addHtml(filename='Baidu.html', html_info=requests.get('https://baike.baidu.com/item/%E7%BE%8E%E5%A5%BD%E4%BA%8B%E7%89%A9/19841687?fr=aladdin').text)
    e.addImage(r'picture\反正要等明天，等冬天，等下雪，顺便就等等你喽-62932-3.jpg','Beautifulgile.jpg')
    e.addImage(r'picture\壁纸5 - 小猫咪.jpg','littercat.jpg')
    e.addFile(r'file\新三板的测试案例.xlsx')
    # e.addFiles(r'files')
    e.sendMail(['tingyxxxx@163.com','3xxxxxx@qq.com','tingxxxxxx@gmail.com'])
